package com.schoolvisitors.service;

import com.schoolvisitors.dto.CreateTimeSlotDto;
import com.schoolvisitors.entity.TimeSlot;
import com.schoolvisitors.exception.BusinessException;
import com.schoolvisitors.repository.TimeSlotRepository;
import com.schoolvisitors.response.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalTime;
import java.util.List;

@Slf4j
@Service
public class TimeSlotService {
    private final TimeSlotRepository timeSlotRepository;


    public TimeSlotService(TimeSlotRepository timeSlotRepository) {
        this.timeSlotRepository = timeSlotRepository;
    }

    @Transactional(rollbackFor = Exception.class)
    public void createTimeSlot(CreateTimeSlotDto createTimeSlotDto) {
        LocalTime startTime = createTimeSlotDto.getStartTime();
        LocalTime endTime = createTimeSlotDto.getEndTime();

        List<TimeSlot> TimeSlots = timeSlotRepository.findOverlappingTimeSlotForUpdate(startTime, endTime);

        if (startTime != null && startTime == endTime){
            throw new BusinessException(ResultCode.START_END_TIME_EQUAL);
        }
        // 时间重叠
        if (!TimeSlots.isEmpty()) {
            throw new BusinessException(ResultCode.TIME_SLOT_CONFLICT);
        }

        TimeSlot newTimeSlot = new TimeSlot();
        newTimeSlot.setStartTime(startTime);
        newTimeSlot.setEndTime(endTime);
        newTimeSlot.setType((short) 1);
        timeSlotRepository.save(newTimeSlot);
    }

    public TimeSlot getTimeSlotById(Long id){
        return timeSlotRepository.findByIdAndDeleteFalse(id);
    }
    public List<TimeSlot> getAllTimeSlots() {
        return timeSlotRepository.findAllByDeleteFalseOrderByStartTimeAsc();
    }

    public void deleteTimeSlot(Long id) {
        TimeSlot timeSlot = timeSlotRepository.findById(id).orElseThrow(() -> new BusinessException(ResultCode.TIME_SLOT_NOT_FOUND));
        timeSlot.setDelete(true);
        timeSlotRepository.save(timeSlot);
    }
}
